﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace WindowsFormsApplication1.common
{
    /// <summary>
    ///版本号：  V1.0
    ///创建人：  奇剑藏锋
    ///电子邮箱：xiefengdaxia123@163.com
    ///创建时间：2018-06-01 11:13:57
    ///描述：
    /// </summary>
    class HttpHelper
    {
        public static HttpWebResponse CreateGetHttpResponse(string url, int timeout, string userAgent, CookieCollection cookies)
        {
            HttpWebRequest httpWebRequest;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(HttpHelper.CheckValidationResult);
                httpWebRequest = (WebRequest.Create(url) as HttpWebRequest);
                httpWebRequest.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                httpWebRequest = (WebRequest.Create(url) as HttpWebRequest);
            }
            httpWebRequest.Method = "GET";
            httpWebRequest.Headers.Add("Accept-Encoding", "gzip");
            if (cookies != null)
            {
                httpWebRequest.CookieContainer = new CookieContainer();
                httpWebRequest.CookieContainer.Add(cookies);
            }
            return httpWebRequest.GetResponse() as HttpWebResponse;
        }

        public static HttpWebResponse CreatePostHttpResponse(string url, string param, CookieCollection cookies, int timeout = 0)
        {
            HttpWebRequest httpWebRequest = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                httpWebRequest = (WebRequest.Create(url) as HttpWebRequest);
            }
            else
            {
                httpWebRequest = (WebRequest.Create(url) as HttpWebRequest);
            }
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/json";
            if (timeout > 0)
            {
                httpWebRequest.Timeout = timeout;
            }
            if (cookies != null)
            {
                httpWebRequest.CookieContainer = new CookieContainer();
                httpWebRequest.CookieContainer.Add(cookies);
            }
            //httpWebRequest.CookieContainer = new CookieContainer();
            //Cookie cookie = new Cookie("Hm_lvt_6fdb24d6391d5b4d7a10eb05d60c8c78", "1513680004");
            //Cookie cookie2 = new Cookie("SESSION", "721a2817-1eb3-4717-b075-8587a9781677");
            // httpWebRequest.CookieContainer.Add(cookie);
            if (param != string.Empty)
            {

                //byte[] bytes = Encoding.ASCII.GetBytes(param);
                byte[] bytes = Encoding.UTF8.GetBytes(param);
                using (Stream requestStream = httpWebRequest.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                }
            }
            string[] values = httpWebRequest.Headers.GetValues("Content-Type");
            return httpWebRequest.GetResponse() as HttpWebResponse;
        }

        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)
        {
            HttpWebRequest httpWebRequest = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                httpWebRequest = (WebRequest.Create(url) as HttpWebRequest);
            }
            else
            {
                httpWebRequest = (WebRequest.Create(url) as HttpWebRequest);
            }
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/json";
            if (cookies != null)
            {
                httpWebRequest.CookieContainer = new CookieContainer();
                httpWebRequest.CookieContainer.Add(cookies);
            }
            if (parameters != null && parameters.Count != 0)
            {
                StringBuilder stringBuilder = new StringBuilder();
                int num = 0;
                foreach (string current in parameters.Keys)
                {
                    if (num > 0)
                    {
                        stringBuilder.AppendFormat("&{0}={1}", current, parameters[current]);
                    }
                    else
                    {
                        stringBuilder.AppendFormat("{0}={1}", current, parameters[current]);
                        num++;
                    }
                }
                byte[] bytes = Encoding.ASCII.GetBytes(stringBuilder.ToString());
                using (Stream requestStream = httpWebRequest.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                }
            }
            string[] values = httpWebRequest.Headers.GetValues("Content-Type");
            return httpWebRequest.GetResponse() as HttpWebResponse;
        }

        public static string GetResponseString(HttpWebResponse webresponse)
        {
            string result;
            if (webresponse.ContentEncoding.ToLower().Contains("gzip"))
            {
                using (GZipStream gZipStream = new GZipStream(webresponse.GetResponseStream(), CompressionMode.Decompress))
                {
                    using (StreamReader streamReader = new StreamReader(gZipStream, Encoding.UTF8))
                    {
                        result = streamReader.ReadToEnd();
                        return result;
                    }
                }
            }
            if (webresponse.ContentEncoding.ToLower().Contains("deflate"))
            {
                using (DeflateStream deflateStream = new DeflateStream(webresponse.GetResponseStream(), CompressionMode.Decompress))
                {
                    using (StreamReader streamReader = new StreamReader(deflateStream, Encoding.UTF8))
                    {
                        result = streamReader.ReadToEnd();
                        return result;
                    }
                }
            }
            using (Stream responseStream = webresponse.GetResponseStream())
            {
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                result = streamReader.ReadToEnd();
            }
            return result;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return errors == SslPolicyErrors.None;
        }
    }
}
